//
//  KDsubscripController.m
//  WangJingApp
//
//  Created by 魏强 on 16/12/30.
//  Copyright © 2016年 KDTech. All rights reserved.
//

#import "KDsubscribController.h"
#import "KDChildSubscirbViewController.h"
#import "KDAddsubscribController.h"
#import "WQSearchController.h"
#import "KDNavigationController.h"
#import "KDSubscribTypeModel.h"
#import "KDSubscripRequestTool.h"
#import "KDGetSubscribedResult.h"
#import "SVProgressHUD.h"
#import "KDTabBarController.h"
#define KDSubscribTypeModelPath [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:@"KDSubscribTypeModel"]
#define kArchivingDataKey @"ArchivingDataKey"
@interface KDsubscribController ()<WQSearchControllerDelegate, KDAddsubscribControllerDelegate>
/**
 *  所有主题数据的集合
 */
@property (nonatomic, strong) NSArray * themeArr;
/**  右边的加号按钮 */
@property (nonatomic, strong) UIButton *rightBtn;
@property (nonatomic, strong) KDNavigationController *searchController;
/**  已订阅模块key值相加和 */
@property (nonatomic, assign) NSInteger roleValue;

@end

@implementation KDsubscribController
#pragma mark - 懒加载区
- (NSArray *)themeArr
{
    if (!_themeArr) {
        
        NSString *plistPath = [[NSBundle mainBundle] pathForResource:@"FakeSubType" ofType:@"plist"];
        
        //    NSArray *data = [[NSArray alloc] initWithContentsOfFile:plistPath];
        _themeArr = [KDSubscribTypeModel objectArrayWithFile:plistPath];
    }
    return _themeArr;
}
- (UIButton *)rightBtn
{
    if (!_rightBtn) {
        _rightBtn = [UIButton buttonWithType:UIButtonTypeCustom] ;
//        [_rightBtn addTarget:self action:@selector(rightBtnClick)];
        [_rightBtn setImage:[UIImage imageNamed:@"add_sub"] forState:UIControlStateNormal];
        [_rightBtn setBackgroundColor:BackGroundColor];
        _rightBtn.width = 44;
    }
    return _rightBtn;
}
#pragma mark - 生命周期区
- (void)dealloc{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}
- (void)viewDidLoad {
    [super viewDidLoad];

    [self setupNavBar];
    //[self setupAllChildViewController];
//    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(subscribGetPushNoty:) name:@"KDSubscribGetPushNoty" object:nil];
    
    [self loadData];
    

    
}
#pragma mark - 板块布置
- (void)setupNavBar{
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithImage:[UIImage imageNamed:@"right_set"] style:UIBarButtonItemStylePlain target:self action:@selector(rightItemClick)];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc]initWithImage:[UIImage imageNamed:@"leftArrow"] style:UIBarButtonItemStylePlain target:self action:@selector(leftItemClick)];

}
- (void)setupAllChildViewController{
    if (self.childViewControllers.count) {
        for (UIViewController *child in self.childViewControllers) {
//            KDLog(@"%@",child.title);
            [child removeFromParentViewController];
            [child.view removeFromSuperview];
        }
//        self.roleValue = 0;
    }
    KDSubscribTypeModel *model = [[KDSubscribTypeModel alloc]init];
    model.name = @"全部";
    model.ID = 0;
    model.parentid= 0;
    
    NSMutableArray *mutaArr = [NSMutableArray arrayWithArray:self.themeArr];
    [mutaArr insertObject:model atIndex:0];
    for (KDSubscribTypeModel *model in mutaArr) {
//        if ([model.isChecked  isEqual: @"1"]) {
            KDChildSubscirbViewController *child = [[KDChildSubscirbViewController alloc]init];
            child.title = model.name;
            child.model = model;
            [self addChildViewController:child];
//        }
    }
    // 4.设置所有标题
    self.needUnderLine = YES;
    [super setupAllTitle];
}
/**
 *  设置所有type的类型为已经订阅
 */
- (void)setCheck{
    for (KDSubscribTypeModel *model in self.themeArr) {
        model.isChecked = @"1";
    }
}
#pragma mark - 事件点击区
/**
 *  添加主题按钮被点击了
 */
- (void)rightItemClick{
    KDAddsubscribController *addCtr = [[KDAddsubscribController alloc]init];
    addCtr.delegate = self;
    addCtr.addArr = [NSMutableArray arrayWithArray:self.themeArr];
    [self.navigationController pushViewController:addCtr animated:YES];
}
/**
 *  搜索按钮被点击了
 */
- (void)searchbarClick{
    WQSearchController *ctr = [[WQSearchController alloc]initWithNibName:@"WQSearchController" bundle:nil];
    ctr.delegate = self;
    self.searchController = [[KDNavigationController alloc]initWithRootViewController:ctr];
    
    [ctr showInViewController:self];
}

- (void)leftItemClick{
    [self dismissViewControllerAnimated:YES completion:nil];
}
#pragma mark - 网络请求区
- (void)loadData{
    KDBaseParam *param = [[KDBaseParam alloc]init];
    param.method = @"earlywaring/getEarlywaringPushUserSubscribe";
    
    [KDSubscripRequestTool getSubscribedModelWithParam:param success:^(KDGetSubscribedResult *responseObejct) {
        if ([responseObejct.code isEqualToString:@"1"]) {
            self.themeArr = responseObejct.data.about_type_id;
            
            [self setCheck];
            [self setupAllChildViewController];
            if (self.type.intValue != 0) {

                self.type = nil;
            }
        }else if ([responseObejct.code isEqualToString:@"E040110000001"]){
            [self.navigationController dismissViewControllerAnimated:NO completion:^{
                KDNewfeatureController *new = [[KDNewfeatureController alloc]init];
                __block KDTabBarController*ctr = (KDTabBarController *)[UIApplication sharedApplication].keyWindow.rootViewController;
                [UIApplication sharedApplication].keyWindow.rootViewController = new;
                [ctr removeObserver];
                [ctr removeFromParentViewController];
                ctr = nil;
            }];
        }else{
            [SVProgressHUD showErrorWithStatus:responseObejct.msg maskType:SVProgressHUDMaskTypeGradient];
        }
    } failure:^(NSError *error) {
        KDLog(@"%@",error);
    }];
//    self.themeArr = [self getFakeData];
}

/**
 *  获取下标位置并划过去:返回值为yes则表示推送过来的消息属于已订阅板块；NO则是非订阅板块
 */
//- (void)checkPageNumWithType:(NSNumber *)type{
//    int i = 0;
//    for (KDSubscribTypeModel *model in self.themeArr) {
//        if (model.col_key.intValue == type.intValue && [model.isChecked  isEqual: @"1"]) {
//            [self switchToPage:i];
//            return ;
//        }
//        i++;
//    }
//    [SVProgressHUD showInfoWithStatus:@"您并未订阅该板块"];
//    
//}
#pragma mark - 通知接收区
/**
 *  接收到推送过来的通知
 */
- (void)subscribGetPushNoty:(NSNotification *)noty{
//    NSDictionary  *notyDic = noty.userInfo;
//    NSNumber *type = notyDic[@"type"];
//    [self checkPageNumWithType:type];
   
    
    
}
#pragma mark - WQSearchControllerDelegate
- (void)questionSearchCancelButtonClicked:(WQSearchController *)controller{
    [controller hide:^{
        KDLog(@"questionSearchCancelButtonClicked");
    }];
}

#pragma mark - KDAddsubscribControllerDelegate
- (void)backViewClickWithThemeArr:(NSArray *)themeArr{
    self.themeArr = themeArr;
//    [self sortedArr];
    
    NSArray *newArr = [KDSubscribTypeModel keyValuesArrayWithObjectArray:themeArr];
    //param.method = @"earlyWaringSetting/updateEarlywaringPushUserSubscribe";
   // param.roleValue = self.roleValue;
    [KDSubscripRequestTool updateAllSubscribeModelWithParam:newArr success:^(KDGetSubscribedResult *responseObejct) {
        if ([responseObejct.code isEqualToString:@"1"]) {
            self.themeArr = themeArr;
            KDLog(@"订阅主题更新成功！");
            [self setupAllChildViewController];
        }else{
            [SVProgressHUD showErrorWithStatus:responseObejct.msg maskType:SVProgressHUDMaskTypeGradient];
        }
    } failure:^(NSError *error) {
        KDLog(@"%@",error);
        [SVProgressHUD showErrorWithStatus:@"网络错误" maskType:SVProgressHUDMaskTypeGradient];
    }];
}
@end
